package com.calabar.flume.tcp.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

public class TCPClient {

    private final String host;
    private final int port;

    public TCPClient() {
        this(8800);
    }

    public TCPClient(int port) {
        this("localhost", port);
    }

    public TCPClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group);// 注册线程池
            b.channel(NioSocketChannel.class); // 使用NioSocketChannel来作为连接用的channel类
            b.remoteAddress(new InetSocketAddress(this.host, this.port)); // 绑定连接端口和host信息
            b.option(ChannelOption.SO_BACKLOG, 1024 * 8);// 配置TCP参数
            b.option(ChannelOption.SO_BACKLOG, 1024 * 8);// 设置tcp缓冲区
            b.option(ChannelOption.SO_SNDBUF, 32 * 1024);// 设置发送缓冲大小
            b.option(ChannelOption.SO_RCVBUF, 32 * 1024); // 这是接收缓冲大小
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    System.out.println("connected...");
                    ch.pipeline().addLast(new TCPClientHandler());
                }
            });
            System.out.println("created..");

            ChannelFuture cf = b.connect().sync(); // 异步连接服务器
            System.out.println("connected..."); // 连接完成

            cf.channel().closeFuture().sync(); // 异步等待关闭连接channel
            System.out.println("closed.."); // 关闭完成
        } finally {
            group.shutdownGracefully().sync(); // 释放线程池资源
        }
    }

    public static void main(String[] args) throws Exception {
        new TCPClient("127.0.0.1", 8800).start(); // 连接127.0.0.1/8800，并启动
    }
}